#ifndef STX_PLATFORM_POSIX_THREAD_SPIN_LOCK_HPP
#define STX_PLATFORM_POSIX_THREAD_SPIN_LOCK_HPP

#include <stx/platform/posix/thread/common.hpp>

namespace stx {

namespace posix {

class spin_lock: noncopyable
{
public:
    
    typedef spin_lock this_type;
    
    spin_lock(int process_shared)
    {
        int ret = pthread_spin_init(&handle_, process_shared);
        if (ret) {
            STX_THROW_SYSTEM_ERROR_VAL(ret, "pthread_spin_init");
        }
    }
    
    ~spin_lock()
    {
        int ret = pthread_spin_destroy(&handle_);
        if (ret) {
            STX_DESTRUCTOR_SYSTEM_ERROR_VAL(ret, "pthread_spin_destroy");
        }
    }
    
    void lock()
    {
        int ret = pthread_spin_lock(&handle_);
        if (ret) {
            STX_THROW_SYSTEM_ERROR_VAL(ret, "pthread_spin_lock");
        }
    }
    
    bool try_lock()
    {
        int ret = pthread_spin_trylock(&handle_);
        if (ret == EBUSY) {
            return false;
        } else {
            STX_THROW_SYSTEM_ERROR_VAL(ret, "pthread_spin_trylock");
        }
        return true;
    }
    
    void unlock()
    {
        int ret = pthread_spin_unlock(&handle_);
        if (ret) {
            STX_THROW_SYSTEM_ERROR_VAL(ret, "pthread_spin_unlock");
        }
    }
    
    typedef pthread_spinlock_t handle_type;
    
    handle_type* handle()
    {
        return &handle_;
    }
    
    const handle_type* handle() const
    {
        return &handle_;
    }
    
private:
    
    handle_type handle_;
};

} // namespace posix

} // namespace stx

#endif // STX_PLATFORM_POSIX_THREAD_SPIN_LOCK_HPP
